package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.ImageDao;
import com.leoman.dao.LeaveMessageDao;
import com.leoman.entity.Comment;
import com.leoman.entity.LeaveMessage;
import com.leoman.entity.User;
import com.leoman.service.LeaveMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * LeaveMessageServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:58.
 */
@Service
public class LeaveMessageServiceImpl implements LeaveMessageService {

    @Autowired
    private LeaveMessageDao leaveMessageDao;

    @Autowired
    private ImageDao imageDao;

    @Override
    public List<LeaveMessage> findAll() {
        return leaveMessageDao.findAll();
    }

    @Override
    public Page<LeaveMessage> find(int pageNum, int pageSize) {
        return leaveMessageDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<LeaveMessage> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public LeaveMessage getById(int id) {
        return leaveMessageDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        leaveMessageDao.delete(id);
    }

    @Override
    public LeaveMessage create(LeaveMessage leaveMessage) {
        return leaveMessageDao.save(leaveMessage);
    }

    @Override
    public LeaveMessage update(LeaveMessage leaveMessage) {
        return leaveMessageDao.save(leaveMessage);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public Page<Comment> iPageForApp(final Integer userId, final Integer type, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<LeaveMessage> leaveMessagePage = leaveMessageDao.findAll(new Specification<LeaveMessage>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<LeaveMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (type == 1) {
                    // 我的留言
                    predicateList.add(cb.equal(root.get("user").get("id").as(Integer.class), userId));
                } else {
                    // 别人对我的留言
                    predicateList.add(cb.equal(root.get("sourceUser").get("id").as(Integer.class), userId));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, pageRequest);

        List<Comment> list = new ArrayList<>();

        for (LeaveMessage leaveMessage : leaveMessagePage.getContent()) {
            list.add(getComment(leaveMessage, type));
        }

        return new PageImpl(list, pageRequest, leaveMessagePage.getTotalElements());
    }

    private Comment getComment(LeaveMessage leaveMessage, Integer type) {
        Comment comment = new Comment();
        User user;

        if (type == 1) {
            user = leaveMessage.getSourceUser();
        } else {
            user = leaveMessage.getUser();
        }

        comment.setId(leaveMessage.getId());
        comment.setUserId(user.getId());
        comment.setNickName(user.getNickName());
        comment.setAvatar(user.getAvatar());
        comment.setContent(leaveMessage.getContent());
        comment.setImageList(imageDao.findListByParams(leaveMessage.getId(), Constant.SOURCE_TYPE_LEAVE));
        comment.setCreateTime(leaveMessage.getCreateTime());

        if (leaveMessage.getIsRead().equals(Constant.USER_STATUS_NO)) {
            leaveMessage.setIsRead(Constant.USER_STATUS_YES);
            leaveMessageDao.save(leaveMessage);
        }

        return comment;
    }
}